import { getGiftList, getGiftListByNamespace } from '@/api/gift'
import {allSite} from '@/api/site'
import {getExpressList, getExpressListByNamespace} from '@/api/info'
import {PRINTER} from '@/utils/cookie'

// initial state
const debug = process.env.NODE_ENV !== 'production'

const state = {
  gifts: [],
  kktypes: [],
  allSites: [],
  currentSite: ''
}

// getters
const getters = {
  availableGifts: (state) => {
    return state.gifts.filter(e => e.status === 'ENABLE')
  },
  availableKKTypes: (state) => {
    return state.kktypes.filter(e => e.status === 'ENABLE')
  }
  //   cartProducts: (state, getters, rootState) => {
  //     return state.items.map(({ id, quantity }) => {
  //       const product = rootState.products.all.find(product => product.id === id)
  //       return {
  //         title: product.title,
  //         price: product.price,
  //         quantity
  //       }
  //     })
  //   },

//   cartTotalPrice: (state, getters) => {
//     return getters.cartProducts.reduce((total, product) => {
//       return total + product.price * product.quantity
//     }, 0)
//   }
}

// actions
const actions = {
  async getGiftList ({state, commit, rootState}) {
    try {
      let result
      if (rootState.role === PRINTER) {
        result = await getGiftListByNamespace(state.currentSite)
      } else {
        result = await getGiftList(true)
      }
      if (result.status === 200 && result.data.code === 200) {
        let gifts = result.data.data.filter((e, i, a) => {
          return e.status === 'ENABLE' && e.resourceDesc.search(/^API_/) === -1
        })
        commit('saveGifts', gifts)
      } else {
        throw new Error('获取数据失败')
      }
    } catch (err) {
      // this.$message.error('获取数据失败')
      console.log('获取数据失败', err)
    }
  },
  async getKktypeList ({state, commit, rootState}) {
    try {
      let result
      if (rootState.role === PRINTER) {
        result = await getExpressListByNamespace(state.currentSite)
      } else {
        result = await getExpressList(true)
      }
      if (result.status === 200 && result.data.code === 200) {
        commit('saveKKTypes', result.data.data)
      } else {
        throw new Error('快递列表获取失败')
      }
    } catch (err) {
      console.log(err)
    }
  },
  async getAllSites ({commit, dispatch}) {
    try {
      let result = await allSite()

      if (result.status === 200 && result.data.code === 200) {
        let sites = result.data.data
        commit('saveSites', sites)
        let site = sites.filter(e => e.hostName === debug ? 'localhost:8002' : window.location.host)[0]
        commit('changeSite', site.namespace)
        commit('saveGifts', [])
        commit('saveKKTypes', [])
        // dispatch('getGiftList')
        // dispatch('getKktypeList')
      } else {
        throw new Error('获取数据失败')
      }
    } catch (err) {
      // this.$message.error('获取数据失败')
      console.log('获取数据失败', err)
    }
  },
  async changeCurrentSite ({commit, dispatch}, namespace) {
    commit('changeSite', namespace)
    commit('saveGifts', [])
    commit('saveKKTypes', [])
    dispatch('getGiftList')
    dispatch('getKktypeList')
  }
  //   checkout ({ commit, state }, products) {
  //     const savedCartItems = [...state.items]
  //     commit('setCheckoutStatus', null)
  //     // empty cart
  //     commit('setCartItems', { items: [] })
  //     shop.buyProducts(
  //       products,
  //       () => commit('setCheckoutStatus', 'successful'),
  //       () => {
  //         commit('setCheckoutStatus', 'failed')
  //         // rollback to the cart saved before sending the request
  //         commit('setCartItems', { items: savedCartItems })
  //       }
  //     )
  //   },

//   addProductToCart ({ state, commit }, product) {
//     commit('setCheckoutStatus', null)
//     if (product.inventory > 0) {
//       const cartItem = state.items.find(item => item.id === product.id)
//       if (!cartItem) {
//         commit('pushProductToCart', { id: product.id })
//       } else {
//         commit('incrementItemQuantity', cartItem)
//       }
//       // remove 1 item from stock
//       commit('products/decrementProductInventory', { id: product.id }, { root: true })
//     }
//   }
}

// mutations
const mutations = {
  saveGifts (state, gifts) {
    state.gifts = gifts.filter((e, i, a) => {
      return e.status === 'ENABLE' && e.resourceDesc.search(/^API_/) === -1
    })
  },
  saveKKTypes (state, kktypes) {
    state.kktypes = kktypes.filter((e, i, a) => {
      return e.status === 'ENABLE' && e.kkType.search(/^API_/) === -1
    })
  },
  saveSites (state, sites) {
    state.allSites = sites
  },
  changeSite (state, namespace) {
    state.currentSite = namespace
  }
  //   pushProductToCart (state, { id }) {
  //     state.items.push({
  //       id,
  //       quantity: 1
  //     })
  //   },

  //   incrementItemQuantity (state, { id }) {
  //     const cartItem = state.items.find(item => item.id === id)
  //     cartItem.quantity++
  //   },

  //   setCartItems (state, { items }) {
  //     state.items = items
  //   },

//   setCheckoutStatus (state, status) {
//     state.checkoutStatus = status
//   }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
